/*
 * Copyright (c) 2016. jiangyc at <710183940@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.jopenlab.jlog.api;

import com.jopenlab.jlog.api.spi.LogBinder;

import java.util.ServiceLoader;

/**
 * The factory class that generates the Log class.This class will load all the implementation classes of LogBinder,
 *     according to the weight of LogBinder, find a suitable implementation class. LogFactory will use this
 *     implementation class to generate a Log instance
 */
public class LogFactory {
    /**
     * all the implementation classes for LogBinder.
     */
    private static ServiceLoader<LogBinder> logBinders = null;
    /** current logBinder */
    private static LogBinder logBinder = null;

    /**
     * Static code block. Loads all the implementation classes for LogBinder.
     */
    static {
        // load all implementation classes for LogBinder
        logBinders = ServiceLoader.load(LogBinder.class);

        for (LogBinder tmp : logBinders) {
            if (!tmp.isAvailable()) {
                continue;
            }
            logBinder = (logBinder == null || tmp.getWeight() > logBinder.getWeight()) ? tmp : logBinder;
        }

        if (logBinder == null) {
            throw new UnsupportedOperationException("Can not find a implementation class for com.jopenlab.jlog.api.spi.LogBinder");
        }
    }

    /**
     * Get all the implementation classes for LogBinder.
     * @return the implementation classes for LogBinder.s
     */
    public static ServiceLoader<LogBinder> getServiceLoader() {
        return logBinders;
    }

    /**
     * Generates a Log instance, using the given class name as the name of the log class
     * @param c the class that as the name of log
     * @return a log implementation
     * @see LogBinder#getLog(String)
     */
    public static Log getLog(Class<?> c) {
        return getLog(c.getName());
    }

    /**
     * Generates a Log instance, using the given string as the name of the log class
     * @param name the given log name
     * @return a log implementation
     * @see LogBinder#getLog(String)
     */
    public static Log getLog(String name) {
        return logBinder.getLog(name);
    }
}
